<template>
  <div>
    <!-- 查询表单 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="场景名称">
          <el-input
            v-model.trim="searchModel.title"
            placeholder="请输入场景名称"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchModel.status" placeholder="请选择状态">
            <el-option label="全部" :value="null" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" color="#ea5b24" @click="search()"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            color="#ea5b24"
            @click="showDialog(0, null)"
            v-if="pinia.isShow[159]"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="场景名称" />
        <el-table-column prop="remark" label="说明" />
        <el-table-column prop="bizPlatform" label="终端产品">
          <template v-slot:default="scope"
            >{{ judgePlatform(scope.row.bizPlatform) }}
          </template>
        </el-table-column>
        <el-table-column prop="appPlatform" label="终端平台">
          <template v-slot:default="scope"
            >{{ judgePlatform(scope.row.appPlatform) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot:default="scope"
            >{{
              scope.row.status == null
                ? ""
                : scope.row.status == 0
                ? "禁用"
                : "启用"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="payMethodNames" label="支付方式" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column fixed="right" width="80" label="操作">
          <template v-slot:default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="showDialog(1, scope.row)"
              v-if="pinia.isShow[160]"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>

    <!--添加/编辑管理员表单 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      center="true"
      modal="true"
      width="30%"
    >
      <el-form :model="configModel" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="名称："
          :label-width="editFormLabelWidth"
          prop="title"
        >
          <el-input
            v-model.trim="configModel.title"
            placeholder="请输入场景名称"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="说明："
          :label-width="editFormLabelWidth"
          prop="remark"
        >
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            v-model.trim="configModel.remark"
            autocomplete="off"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item
          label="终端产品："
          :label-width="editFormLabelWidth"
          prop="bizPlatform"
          @change="showPayMethod"
        >
          <el-radio-group v-model="configModel.bizPlatform">
            <el-radio label="wnsj">华行通</el-radio>
            <el-radio label="kyx">货通宝</el-radio>
            <el-radio label="cxw">车讯网</el-radio>
            <el-radio label="ybt">壹佰通</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="终端平台："
          :label-width="editFormLabelWidth"
          prop="appPlatform"
          @change="showPayMethod"
        >
          <el-radio-group v-model="configModel.appPlatform">
            <el-radio label="wx">微信小程序</el-radio>
            <el-radio label="alipay">支付宝小程序</el-radio>
            <el-radio label="android">android客户端</el-radio>
            <el-radio label="ios">IOS客户端</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="支付方式："
          :label-width="editFormLabelWidth"
          prop="payMethodIdArr"
          v-if="isShowPayMethod"
        >
          <el-select
            v-model="configModel.payMethodIdArr"
            multiple
            placeholder="请选择支付方式"
            class="select-roles"
          >
            <el-option
              v-for="item in payMethod.data"
              :value="item['value']"
              :label="item['label']"
              :key="item['value']"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="状态："
          :label-width="editFormLabelWidth"
          prop="status"
        >
          <el-radio-group v-model="configModel.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="formSubmit(ruleFormRef)"
            color="#ea5b24"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import {
  findPaySceneListApi,
  editPaySceneApi,
  findPaymanagement,
} from "../../../api/index";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 控制对话框
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogType = ref(0);
const editFormLabelWidth = "100px";

const isShowPayMethod = ref(false);
// 搜索模型
const searchModel: any = reactive({
  title: null,
  status: null,
  pageNum: page,
  pageSize: size,
});
// 添加/编辑模型
const configModel = reactive({
  id: null,
  title: null,
  remark: null,
  appPlatform: null,
  bizPlatform: null,
  payMethodIdArr: [],
  payMethodIds: null,
  status: null,
});

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入场景名称", trigger: "blur" }],
  bizPlatform: [{ required: true, message: "请选择终端产品", trigger: "blur" }],
  appPlatform: [{ required: true, message: "请选择终端平台", trigger: "blur" }],
  payMethodIdArr: [
    { required: true, message: "请选择支付方式", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

// 过滤终端显示
function judgePlatform(item) {
  switch (item) {
    case "wnsj":
      return "华行通";
    case "kyx":
      return "货通宝";
    case "cxw":
      return "车讯网";
    case "ybt":
      return "壹佰通";
    case "wx":
      return "微信小程序";
    case "alipay":
      return "支付宝小程序";
    case "android":
      return "android客户端";
    case "ios":
      return "IOS客户端";
    default:
      return "";
  }
}

// 翻页
let flipData = reactive({
  pageNum: page,
  pageSize: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.pageNum = page.value;
  searchConfig(flipData);
};

// 搜索支付场景
const search = () => {
  page.value = 1;
  searchParmSearch();
  searchConfig(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

//条件查询支付场景列表
const searchConfig = (searchModel) => {
  findPaySceneListApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.items;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

const showPayMethod = () => {
  if (configModel.appPlatform && configModel.bizPlatform) {
    configModel.payMethodIdArr = [];
    findAllRoles({
      appPlatform: configModel.appPlatform,
      bizPlatform: configModel.bizPlatform,
    });
    isShowPayMethod.value = true;
  }
};

// 控制添加/编辑dialog显示
const showDialog = (type: number, row) => {
  dialogVisible.value = true;
  dialogType.value = type;
  ruleFormRef.value ? ruleFormRef.value.clearValidate() : false;
  if (type === 0) {
    dialogTitle.value = "添加支付场景";
    Object.keys(configModel).forEach((key) => (configModel[key] = ""));
  } else {
    dialogTitle.value = "编辑支付场景";
    configModel.id = row.id;
    configModel.title = row.title;
    configModel.remark = row.remark;
    configModel.bizPlatform = row.bizPlatform;
    configModel.appPlatform = row.appPlatform;
    configModel.status = row.status;
    showPayMethod();
    configModel.payMethodIdArr = [];
    if (row.payMethodIds) {
      row.payMethodIds.split(",").forEach((val) => {
        configModel.payMethodIdArr.push(parseInt(val));
      });
    }
  }
};

/**
 * 添加/编辑
 */
const formSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      configModel.payMethodIds = configModel.payMethodIdArr.join(",");
      editPaySceneApi(configModel).then((res) => {
        if (res.data.code === 2000) {
          ElMessage({
            message: dialogType.value == 0 ? "添加成功." : "编辑成功.",
            type: "success",
          });
          searchConfig(searchModel);
        } else {
          switch (res.data.code) {
            default:
              dialogType.value == 0
                ? ElMessage.error("添加失败.")
                : ElMessage.error("编辑失败.");
              break;
          }
        }
      });

      Object.keys(configModel).forEach((key) => (configModel[key] = ""));
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 查询所有的支付方式
let payMethod: any = reactive([]);
const findAllRoles = (param) => {
  findPaymanagement(param).then((res) => {
    if (res.data.code === 2000) {
      let dataList = res.data.data;
      payMethod.data = Array.from(dataList).map((item, idx) => ({
        value: item["id"],
        label: item["showName"],
      }));
    } else {
      ElMessage.error("查询支付方式失败");
    }
  });
};

onMounted(() => {
  searchConfig(searchModel);
});
</script>

<style>
.select-roles {
  width: 100%;
}
</style>
